package top.kaoshanji.q1ch06a.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.kaoshanji.q1ch06a.handler.LoginInterceptor;

/**
 * 代码清单-q1ch06a-197页a：定义一个Web配置类
 * @author kaoshanji
 * ^_^
 * create time 2025/5/21 17:59
 */
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    // 代码清单-q1ch06a-198页a：注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/***")
                .excludePathPatterns("/login/**")
                .excludePathPatterns("/static/**");
    }

    // 代码清单-q1ch06a-201页a1：注册一个类型转换器
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new CustomConverter());
    }

    // 代码清单-q1ch06a-208页b：处理静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
        registry.addResourceHandler("/dist/**").addResourceLocations("classpath:/dist/");
    }

    // 代码清单-q1ch06a-229页a：跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/user/**")
                .allowedMethods("GET", "POST")
                .allowedOrigins("http://xxx.com")
                .allowCredentials(true).maxAge(3600);

    }
}
